package org.example.web;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.ResourceHandler;
import org.eclipse.jetty.server.handler.HandlerList;
import org.eclipse.jetty.server.handler.DefaultHandler;
import org.eclipse.jetty.util.resource.Resource;
import org.example.database.HikariDatabaseConnection;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class WebServer {
    private static final int PORT = 8080;
    private Server server;

    public void start() throws Exception {
        server = new Server(PORT);
        
        // 创建静态资源处理器
        ResourceHandler resourceHandler = new ResourceHandler();
        resourceHandler.setBaseResource(Resource.newResource("src/main/resources/static"));
        resourceHandler.setDirectoriesListed(false);
        resourceHandler.setWelcomeFiles(new String[]{"mixue.html"});
        
        // 创建处理器列表
        HandlerList handlers = new HandlerList();
        handlers.addHandler(resourceHandler);
        handlers.addHandler(new DefaultHandler());
        
        server.setHandler(handlers);
        
        server.start();
        System.out.println("Web服务器已启动，访问地址: http://localhost:" + PORT);
        
        // 测试数据库连接
        testDatabaseConnection();
    }
    
    public void stop() throws Exception {
        if (server != null) {
            server.stop();
            System.out.println("Web服务器已停止");
        }
    }
    
    private void testDatabaseConnection() {
        try (Connection conn = HikariDatabaseConnection.getConnection()) {
            if (conn != null && !conn.isClosed()) {
                System.out.println("数据库连接成功！");
                
                // 执行一个简单的查询来测试连接
                PreparedStatement stmt = conn.prepareStatement("SELECT 1");
                ResultSet rs = stmt.executeQuery();
                if (rs.next()) {
                    System.out.println("数据库查询测试成功！");
                }
                rs.close();
                stmt.close();
            } else {
                System.out.println("数据库连接失败！");
            }
        } catch (SQLException e) {
            System.err.println("数据库连接测试失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
    
    public static void main(String[] args) {
        WebServer webServer = new WebServer();
        try {
            webServer.start();
            // 保持服务器运行
            Thread.currentThread().join();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}